# coding:utf-8

import logging

from flask import jsonify
from flask import request

from .. import db
from ..base import base
from ..models.LoggerInfoBlack import LoggerInfoBlack

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


@base.route('/logInfoBlack/queryBlackLogList', methods=['GET'])
def queryBlackLogList():
    # 获取查询参数
    remark_val = request.args.get('remark')
    ip_val = request.args.get('ip')
    page = request.args.get('page', 0, type=int)  # 页码，默认为第1页
    per_page = request.args.get('per_page', 30, type=int)  # 每页记录数，默认为10条
    try:
        query = LoggerInfoBlack.query
        # 根据参数添加条件
        if remark_val is not None:
            query = query.filter(LoggerInfoBlack.remark.like(f"%{remark_val}%"))
        if ip_val is not None:
            query = query.filter(LoggerInfoBlack.ip == ip_val)
        # 执行查询
        query = query.order_by(LoggerInfoBlack.id.desc())  # 按照 降序排序
        paginated_query = query.paginate(page=page, per_page=per_page, error_out=False)
        # 执行查询并返回结果
        # 将查询结果转换为字典列表，包含所有字段
        results_list = [log_info.to_json() for log_info in paginated_query.items]
        return jsonify({
            'total': paginated_query.total,
            'pages': paginated_query.pages,
            'current_page': paginated_query.page,
            'per_page': paginated_query.per_page,
            'results': results_list
        }), 200
    except Exception as e:
        logger.error("queryLogList|查询历史数据服务异常：", str(e))
        return jsonify({'error': str(e)}), 500


@base.route('/logInfoBlack/deleteById', methods=['GET'])
def deleteById4Black():
    id = request.args.get('id')
    logger.info(f"deleteById|删除日志记录参数:{id}")
    try:
        # 查询要删除的记录
        logger_info = LoggerInfoBlack.query.get(id)
        # 检查记录是否存在
        if logger_info is None:
            return jsonify({'message': 'LoggerInfo not found'}), 404
        # 删除记录
        db.session.delete(logger_info)
        db.session.commit()  # 提交更改
        return jsonify({'message': 'LoggerInfo deleted successfully'}), 200
    except Exception as e:
        db.session.rollback()  # 在异常情况下回滚
        logger.error("deleteById|删除日志记录服务异常：", str(e))
        return jsonify({'error': str(e)}), 500


@base.route('/logInfoBlack/deleteAll', methods=['GET'])
def deleteAll4Black():
    # 获取请求参数
    try:
        deleted_count = db.session.query(LoggerInfoBlack).delete()  # 删除所有记录
        db.session.commit()  # 提交更改
        return jsonify({'message': f'{deleted_count} 日志全部清空'}), 200
    except Exception as e:
        db.session.rollback()  # 在异常情况下回滚
        logger.error("delete_all_logger_info|删除日志记录服务异常：", str(e))
        return jsonify({'error': str(e)}), 500


@base.route('/logInfoBlack/updateLogInfoByIp4Black', methods=['POST'])
def updateLogInfoByIp4Black(data):
    if not data or 'ip' not in data:
        return 0
    try:
        # 查找现有记录，使用 unique_code 进行判断
        existing_log_info = LoggerInfoBlack.query.filter_by(ip=data['ip']).first()

        if not existing_log_info:
            logger.info(f"updateLogInfoByIp4Black|新增数据:{data}")
            # 如果记录不存在，创建新记录
            new_user_info = LoggerInfoBlack(
                type=data.get('type'),
                info=data.get('info'),
                remark=data.get('remark'),
                ip=data.get('ip'),
                url=data.get('url'),
            )
            db.session.add(new_user_info)
            db.session.commit()
            return new_user_info.id
        else:
            logger.info(f"updateLogInfoByIp4Black|变更数据:{data}")
            # 更新现有记录
            # 仅更新传入字段不为空的字段
            for key, value in data.items():
                if value is not None and key != 'ip':
                    setattr(existing_log_info, key, value)
            # 提交更新
            db.session.commit()
            return existing_log_info.id
    except Exception as e:
        db.session.rollback()  # 回滚事务
        logger.error("updateLogInfoByIp4Black|保存日志信息到数据库发生异常：", str(e))
        return 0
